<?php
namespace App\Repositories\Transportation;

use App\Exceptions\API\APIException;
use App\Exceptions\API\BadRequest;
use App\Models\Transportation;
class TransportationDBRepository implements TransportationRepository
{

    public function getPaginator(TransportationFilter $transportationFilter)
    {
        $query = $this->getDBQuery($transportationFilter);

        return $query->paginate($transportationFilter->getPerPage());
    }

    protected function getDBQuery(TransportationFilter $transportationFilter)
    {
        $transportationQuery = Transportation::query();
        $transportationQuery->with('users');
        $name = $transportationFilter->getName();
        if ($name) {
            $transportationQuery->whereHas('users' , function ($query) use($name) {
                $query->where('name', 'like', '%'.$name.'%');
            });

        }
        if ($userId = $transportationFilter->getUserId()) {
            $transportationQuery->where('user_id', $userId);
        }

        $startTime = $transportationFilter->getStartTime();
        $endTime = $transportationFilter->getEndTime();
        if($startTime && $endTime){
            $transportationQuery->where('riding_time','>=',$startTime)
                ->where('riding_time','<=',$endTime);
        }

        return $transportationQuery;
    }

}
